package org.ah.ssm.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.ah.ssm.ahutils.AhConst;
import org.ah.ssm.ahutils.AhUtils;
import org.ah.ssm.entity.Examinee;
import org.ah.ssm.entity.Question;
import org.ah.ssm.service.QuestionService;
import org.springframework.stereotype.Service;

@Service
public class QuestionServiceImpl implements QuestionService {

	@Override
	public List<Question> getQs() {
		if (AhUtils.newQs.size() == 0) {
			// 取题
			int nCount = AhConst.QS_COUNT;
			ArrayList<Question> allQs = AhUtils
					.ahGetQsFromFile("/ExamJava.txt");
			if (allQs.size() < AhConst.QS_COUNT) {
				nCount = allQs.size();
			}
			// 随机取题
			Random r = new Random();
			for (int i = 0; i < nCount; i++) {
				int n = r.nextInt(allQs.size());
				Question q = allQs.get(n);
				AhUtils.newQs.add(q);
				allQs.remove(n);
			}
			AhUtils.ahWriteQs();
		}
		return AhUtils.newQs;
	}

	@Override
	public String getUserAnswers(Examinee eUser, List<Question> qs,
			Map<String, String[]> pMap) {
		// 定义变量
		String _lastChar = "";
		int _题号 = -1;
		StringBuilder _sbUserAnswer = new StringBuilder();
		String _userAnswer = "";
		int _正确 = 0, _错误 = 0;
		StringBuilder _sb考试信息 = new StringBuilder(eUser.getExaName() + "\t");
		// 遍历用户提交参数的列表
		for (int i = 0; i < AhUtils.newQs.size(); i++) {
			String key = "opt" + i;
			// 每一道题
			_lastChar = key.substring(key.length() - 1);
			_题号 = Integer.valueOf(_lastChar);
			// StringBuilder清空
			_sbUserAnswer.delete(0, _sbUserAnswer.length());

			for (String s : pMap.get(key)) {
				_sbUserAnswer.append(s);
			}
			_userAnswer = _sbUserAnswer.toString();
			_userAnswer = (_userAnswer == null) ? "" : _userAnswer;
			if (_userAnswer.equals(qs.get(_题号).getAnswer())) {
				// 回答正确
				_sb考试信息.append((_题号 + 1)  + ".√\t");
				_正确++;

			} else {
				// 回答错误
				_sb考试信息.append((_题号 + 1)  + ".X【"
						+ _userAnswer + "】\t");
				_错误++;
			}
		}
		int score = (_正确 * 100) / (_正确 + _错误);
		_sb考试信息.append("得分:" + score);
		AhUtils.ahPrintLog(_sb考试信息.toString());
		return _sb考试信息.toString();
	}
}
